package com.aramis.mydytt.db

import com.aramis.mydytt.ui.bean.MovieDetailBean
import com.aramis.mydytt.ui.bean.MovieItemBean
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.schedulers.Schedulers

/**
 * Description: FavoriteManager
 * @author lizhidan
 * Created: 2021/6/7
 */
object FavoriteManager {

    fun addFavorite(movieItemBean: MovieItemBean): Observable<FavoriteMovieBean?> {
        return addFavorite(movieItemBean.toFavoriteMovieBean())
    }

    fun addFavorite(detailBean: MovieDetailBean): Observable<FavoriteMovieBean?> {
        return addFavorite(detailBean.toFavoriteMovieBean())
    }

    private fun addFavorite(favoriteMovieBean: FavoriteMovieBean): Observable<FavoriteMovieBean?> {
        return Observable.create(ObservableOnSubscribe<FavoriteMovieBean?> { emitter ->
            try {
                val fId = DBManager.db?.favoriteMovieDao()?.insert(favoriteMovieBean)
                if (fId != null && fId > 0) {
                    emitter.onNext(favoriteMovieBean.also { it.id = fId })
                } else {
                    emitter.onError(Throwable("插入失败：fId 不存在"))
                }
            } catch (e: Exception) {
                e.printStackTrace()
                emitter.onError(Throwable("插入失败：${e.javaClass.name}:${e.message}"))
            }
            emitter.onComplete()
        }).subscribeOn(Schedulers.io())
    }


    fun removeFavorite(favoriteMovieId: Long?): Observable<Any?> {
        return Observable.create(ObservableOnSubscribe<Any?> { emitter ->
            try {
                if (favoriteMovieId != null && favoriteMovieId > 0) {
                    DBManager.db?.favoriteMovieDao()?.deleteById(favoriteMovieId)
                    emitter.onNext(Any())
                } else {
                    emitter.onError(Throwable("favoriteMovieId为空或等于0"))
                }
            } catch (e: Exception) {
                e.printStackTrace()
                emitter.onError(Throwable("删除失败：${e.javaClass.name}:${e.message}"))
            }
            emitter.onComplete()
        }).subscribeOn(Schedulers.io())
    }

    fun deleteFavoriteData(dataList: List<MovieItemBean>): Observable<Any?> {
        return Observable.create(ObservableOnSubscribe<Any?> { emitter ->
            try {
                dataList.forEach {
                    if (it.selected) {
                        DBManager.db?.favoriteMovieDao()?.deleteByMovieId(it.id)
                    }
                }
                emitter.onNext(Any())
            } catch (e: Exception) {
                e.printStackTrace()
                emitter.onError(Throwable("删除失败：${e.javaClass.name}:${e.message}"))
            }
            emitter.onComplete()
        }).subscribeOn(Schedulers.io())
    }
}